package com.menu.Controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.menu.Configuration.AlipayConfig;
import com.menu.Configuration.Security.TokenManager;
import com.menu.Service.DataService;
import com.menu.Service.OrderService;
import com.menu.Service.UserService;
import com.menu.Utils.CommonUtil;
import com.menu.Utils.ResponseResult;
import io.swagger.annotations.*;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Api(tags = "无需用户验证接口")
@RestController
@Slf4j
public class BasicContorller {

    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private TokenManager tokenManager;
    @Resource
    private DataService dataService;

    @ApiOperation("验证账号是否合法")
    @ApiImplicitParam(name = "account", value = "账号",dataTypeClass = String.class)
    @GetMapping("/Visitor/verifyAccount")
    public ResponseResult verifyAccount(String account) {
        if (account == null || account.length() < 6 || account.length() > 16) {
            return ResponseResult.error("账号不合法！");
        }
        return userService.verifyAccount(account);
    }

    @ApiOperation("验证邮箱是否合法")
    @ApiImplicitParam(name = "email", value = "邮箱",dataTypeClass = String.class)
    @GetMapping("/Visitor/verifyEmail")
    public ResponseResult verifyEmail(String email) {
        if (email == null || !email.matches(CommonUtil.email)) {
            return ResponseResult.error("邮箱格式有误！");
        }
        return userService.verifyEmail(email);
    }

    @ApiOperation(value = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号",dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "密码",dataTypeClass = String.class),
            @ApiImplicitParam(name = "email", value = "邮箱",dataTypeClass = String.class),
            @ApiImplicitParam(name = "code", value = "验证码",dataTypeClass = String.class)
    })
    @PostMapping("/Visitor/register")
    public ResponseResult register(String account, String password, String email, String code) {
        if (account == null || account.length() < 6 || account.length() > 16) {
            return ResponseResult.error("账号不合法！");
        }
        if (password == null || password.length() < 6 || password.length() > 16) {
            return ResponseResult.error("密码不合法！");
        }
        if (email == null || !email.matches(CommonUtil.email)) {
            return ResponseResult.error("邮箱格式有误！");
        }
        if (code == null || code.length() != 6) {
            return ResponseResult.error("验证码有误！");
        }
        return userService.register(account, password, email, code);
    }

    @ApiOperation(value = "发送验证码")
    @ApiImplicitParam(name = "email", value = "邮箱",dataTypeClass = String.class)
    @GetMapping("/Visitor/sendCode")
    public ResponseResult sendCode(String email) {
        if (email == null || !email.matches(CommonUtil.email)) {
            return ResponseResult.error("邮箱格式有误！");
        }
        return userService.sendCode(email);
    }

    @ApiOperation("用户登录")
    @PostMapping("/User/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", paramType = "query", value = "账号/邮箱",dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", paramType = "query", value = "密码",dataTypeClass = String.class)
    })
    public void  login(String account,String password){}

    @ApiOperation("找回密码")
    @PostMapping("/Visitor/updatePassword")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email",  value = "邮箱",dataTypeClass = String.class),
            @ApiImplicitParam(name = "code",  value = "验证码",dataTypeClass = String.class),
            @ApiImplicitParam(name = "newPassword",value = "新密码",dataTypeClass = String.class)
    })
    public ResponseResult findPassword(String email,String code,String newPassword){
        if (email == null || !email.matches(CommonUtil.email)) {
            return ResponseResult.error("邮箱格式有误！");
        }
        if (newPassword == null || newPassword.length() < 6 || newPassword.length() > 16) {
            return ResponseResult.error("密码不合法！");
        }
        if (code == null || code.length() != 6) {
            return ResponseResult.error("验证码有误！");
        }
        return userService.findPassword(email,code,newPassword);
    }

    @ApiIgnore
    @PostMapping("/Alipay/Callback")
    public ResponseResult alipayCallback(HttpServletRequest httpServletRequest){
        Map requestParams = httpServletRequest.getParameterMap();
        Map<String, String> params = CommonUtil.transToMAP(requestParams);
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, alipayConfig.getAlipay_public_key(),
                    "utf-8",alipayConfig.getSign_type());
            if(!alipayRSACheckedV2){
                log.info("{}验签失败",params.get("out_trade_no"));
                return ResponseResult.error("非法请求，验证不通过");
            }else{
                log.info("{}:验签成功！",params.get("out_trade_no"));
                return orderService.aliCallback(params);
            }
        } catch (AlipayApiException e) {
            log.info("支付宝回调异常",e);
        }
        return orderService.aliCallback(params);
    }

    @ApiOperation("用户以refresh_token刷新token和refresh_token")
    @PostMapping("/User/refresh_token")
    public ResponseResult refreshToken(String refresh_token){
        Map<String, String> userInfoFromToken = tokenManager.getUserInfoFromToken(refresh_token);
        String token = tokenManager.createToken(userInfoFromToken);
        String refreshToken = tokenManager.createRefreshToken(userInfoFromToken);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        map.put("refresh_token",refreshToken);
        return ResponseResult.success(map);
    }

    @ApiOperation("获取大家都在搜")
    @GetMapping("/Visitor/allInSearch")
    public ResponseResult allInSearch(){
        return dataService.allInSearch();
    }
}
